package com.th.controller;

import com.th.util.VerificationUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
public class VerificationController {

    private static final Logger LOGGER = LoggerFactory.getLogger(VerificationController.class);
    public static final String VCODE = "VCODE";

    @GetMapping("/verificationcode")
    public void Verification(HttpServletRequest request, HttpServletResponse response){
        HttpSession session = request.getSession();
        response.setContentType("image/png");
        try {
            ImageIO.write(VerificationUtil.getVCODE(), "png", response.getOutputStream());
        } catch (IOException e) {
            LOGGER.error("程序异常, 详细信息:{}", e.getLocalizedMessage() , e);
            e.printStackTrace();
        }
        //先清空session中的验证码
        session.removeAttribute(VCODE);
        //放入session中
        session.setAttribute(VCODE, VerificationUtil.VCODE);
    }
}
